package cn.chinaflame.pagodas.pool.forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.ThreadFactory;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

public class LightWorkerThread extends ForkJoinWorkerThread{
	public static final String SEARCHTHREAD = "searchthread";//自定义寻灯线程各前缀
	public static final String SENDTHREAD = "sendthread";//自定义安灯线程各前缀
	public static final String CHECKTHREAD = "checkthread";//自定义检查灯位线程各前缀
	public static final String CLEARTHREAD = "clearthread";//自定义清灯线程各前缀
	
	final static ThreadFactory SEARCHTHREADFACTORY = new ThreadFactoryBuilder()    //自定义寻灯线程工厂
	        .setNameFormat("[" + SEARCHTHREAD + "-%d]" ) 
	        .setPriority(Thread.MAX_PRIORITY)
	        .build();  
	final static ThreadFactory SENDTHREADFACTORY = new ThreadFactoryBuilder()  //自定义安灯线程工厂
			.setPriority(Thread.MAX_PRIORITY)
	        .setNameFormat("[" + SENDTHREAD + "-%d]" )  
	        .build(); 
	final static ThreadFactory CHECKTHREADFACTORY = new ThreadFactoryBuilder()  //自定义检查灯位线程工厂
			.setPriority(Thread.MAX_PRIORITY)
	        .setNameFormat("[" + CHECKTHREAD + "-%d]")  
	        .build(); 
	final static ThreadFactory CLEARTHREADFACTORY = new ThreadFactoryBuilder()  //自定义清灯线程工厂
			.setPriority(Thread.MAX_PRIORITY)
	        .setNameFormat("[" + CLEARTHREAD + "-%d]")  
	        .build(); 
	private static ThreadLocal<Integer> taskCounter = new ThreadLocal<Integer>();
	
    protected LightWorkerThread(ForkJoinPool pool) {
        super(pool);
    }
    
    @Override
    protected void onStart() {
        super.onStart();
//        this.setName(name);
        System.out.println("LightWorkerThread: " + getId()+ " : Initializing task counter");
        taskCounter.set(0);
    }
    
    @Override
    protected void onTermination(Throwable exception) {
        System.out.println("LightWorkerThread: " + getId() + " :"
                + taskCounter.get());
        super.onTermination(exception);
    }
    
    public void addTask() {
        int counter = taskCounter.get().intValue();
        counter++;
        taskCounter.set(counter);
    } 
}
